package com.elinkway.infinitemovies.view;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.androidquery.AQuery;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.dao.PreferencesManager;
import com.elinkway.infinitemovies.listener.MyOnAdListener;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.SelfDataConstant;
import com.elinkway.infinitemovies.selfdata.bean.MyDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.utils.AppListUtil;
import com.elinkway.infinitemovies.utils.BitmapUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.MoviesUtils;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.le123.ysdq.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.qq.e.ads.cfg.MultiProcessFlag;
import com.qq.e.ads.nativ.NativeAD;
import com.qq.e.ads.nativ.NativeAD.NativeAdListener;
import com.qq.e.ads.nativ.NativeADDataRef;

import java.util.HashMap;
import java.util.List;

/**
 * Date: 2016-12-28
 * Time: 16:56
 * Description: FIXME
 */
public class GdtNativeAdView implements NativeAdListener {

    private NativeADDataRef adItem;
    private NativeAD nativeAD;
    private AQuery $;
    private Activity activity;
    private String type;
    private MyOnAdListener adListener;
    private View mView;
    private long startRequestTime = 0;
    private String mAdposition;
    private Bitmap bmp = null;
    private boolean splashIsResponse = false;
    private boolean isOutTimeJump = false;
    private boolean isOutTimeControlInVideoDetail = false;

    public GdtNativeAdView(Activity activity, String type, String mAdposition){
        this.activity = activity;
        this.type = type;
        this.mAdposition = mAdposition;
        MultiProcessFlag.setMultiProcess(true);
        $ = new AQuery(activity);
    }

    public GdtNativeAdView(Activity activity, String type, View view, String mAdposition){
        this.activity = activity;
        this.type = type;
        this.mAdposition = mAdposition;
        MultiProcessFlag.setMultiProcess(true);
        mView = view;
        $ = new AQuery(activity, view);
    }

    public MyOnAdListener getAdListener() {
        return adListener;
    }

    public void setAdListener(MyOnAdListener adListener) {
        this.adListener = adListener;
    }

    public void loadAD(String adId){
        if(MoviesUtils.isSelfProduct(activity.getPackageName())){
            startRequestTime = System.currentTimeMillis();
            if(nativeAD == null){
                this.nativeAD = new NativeAD(activity, MoviesConstant.GDT_APP_ID, adId, this);
            }
            int count = 5; // 一次拉取的广告条数：范围1-10
            nativeAD.loadAD(count);
            if ("attach".equals(type)) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(adListener != null){
                            if (!isOutTimeControlInVideoDetail) {
                                adListener.onAdFailed();
                                isOutTimeControlInVideoDetail = true;
                                selfGdtReport(SelfDataConstant.AC_ADREQUEST_OUTTIME);
                                reportGdtOutTime();
                            }
                        }
                    }
                }, 1000);
            }
            reportAdRequestVtwo();
            if("splash".equals(type)){
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(!splashIsResponse){
                            if(adListener != null){
                                isOutTimeJump = true;
                                adListener.onAdFailed();
                                selfGdtReport(SelfDataConstant.AC_ADREQUEST_OUTTIME);
                                reportGdtOutTime();
                            }
                        }
                    }
                }, 3000);
            }
        }
    }

    public void showAD(NativeADDataRef adItem, String type) {
        this.adItem = adItem;
        showAD(type);
    }

    /**
     * 展示原生广告时，一定要先调用onExposured接口曝光广告，否则将无法调用onClicked点击接口
     */
    public void showAD(String type) {
        reportAdShow();
        if("splash".equals(type)){  //启动图
            $.id(R.id.splash_ad_iv).visible();
            $.id(R.id.ad_logo_iv).visible();
            $.id(R.id.splash_ad_iv).image((String) adItem.getImgUrl(), true, true);
            $.id(R.id.ad_logo_iv).image(R.drawable.gdt_ad_logo);
            activity.findViewById(R.id.nativeADContainer).setVisibility(View.VISIBLE);
            adItem.onExposured(mView); // 需要先调用曝光接口
            $.id(R.id.splash_ad_iv).clicked(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    adItem.onClicked(view); // 点击接口
                    reportAdClick();
                }
            });
            if(AppListUtil.isToday(PreferencesManager.getInstance().getSplashGdtMs())){
                int oldTimes = PreferencesManager.getInstance().getSplashGdtShowtimes();
                oldTimes++;
                PreferencesManager.getInstance().setSplashGdtShowtimes(oldTimes);
            }else{
                PreferencesManager.getInstance().setSplashGdtShowtimes(1);
            }
            PreferencesManager.getInstance().setSplashGdtMs(System.currentTimeMillis());
        }else if("banner".equals(type)){
            mView.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, UIs.getScreenWidth()/2);
            mView.findViewById(R.id.home_banner_ad).setLayoutParams(params);
            $.id(R.id.home_banner_ad).image((String) adItem.getImgUrl(), true, true);
            $.id(R.id.ad_logo_iv_banner).visible();
            $.id(R.id.ad_logo_iv_banner).image(R.drawable.gdt_ad_logo);
            $.id(R.id.text_banner_desc).text((String) adItem.getDesc());
            adItem.onExposured(mView); // 需要先调用曝光接口
            $.id(R.id.linear_layout_recommend).clicked(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    adItem.onClicked(view); // 点击接口
                    reportAdClick();
                }
            });
        }else if("one".equals(type)){   //左图右文
            $.id(R.id.ad_logo_iv_one).visible();
            $.id(R.id.ad_logo_iv_one).image(R.drawable.gdt_ad_logo);
            $.id(R.id.ad_left_image_iv_one).image((String) adItem.getImgUrl(), true, true);
            $.id(R.id.text_desc_one).text((String) adItem.getDesc());
            $.id(R.id.text_title_one).text(adItem.getTitle());
            if(mView == null){
                activity.findViewById(R.id.nativeADContainerone).setVisibility(View.VISIBLE);
                adItem.onExposured(activity.findViewById(R.id.nativeADContainerone)); // 需要先调用曝光接口
                activity.findViewById(R.id.nativeADContainerone).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        adItem.onClicked(view); // 点击接口
                        reportAdClick();
                    }
                });
            }else{
                mView.findViewById(R.id.nativeADContainerone).setVisibility(View.VISIBLE);
                adItem.onExposured(mView.findViewById(R.id.nativeADContainerone)); // 需要先调用曝光接口
                mView.findViewById(R.id.nativeADContainerone).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        adItem.onClicked(view); // 点击接口
                        reportAdClick();
                    }
                });
            }
        }else if("two".equals(type)){   //横图文覆
            $.id(R.id.ad_image_iv_two).image((String) adItem.getImgUrl(), true, true);
            $.id(R.id.text_desc_two).text((String) adItem.getDesc());
            if(mView == null){
                activity.findViewById(R.id.nativeADContainertwo).setVisibility(View.VISIBLE);
                adItem.onExposured(activity.findViewById(R.id.nativeADContainertwo)); // 需要先调用曝光接口
                activity.findViewById(R.id.nativeADContainertwo).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        adItem.onClicked(view); // 点击接口
                        reportAdClick();
                    }
                });
                new Thread(){
                    @Override
                    public void run() {
                        bmp =  ImageLoader.getInstance().loadImageSync(adItem.getImgUrl());
                    }
                }.start();

                new Handler().postDelayed(new Runnable(){

                    public void run() {
                        if(!TextUtils.isEmpty(adItem.getImgUrl()) && null != bmp){
                            Bitmap myBitmap = Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth() / 3) , (int)(bmp.getHeight() / 3), true);
                            ((ImageView)activity.findViewById(R.id.gdt_right_bg)).setImageBitmap(BitmapUtils.fastBlur(myBitmap, 5));
                        }
                    }

                }, 300);
            }else{
                mView.findViewById(R.id.nativeADContainertwo).setVisibility(View.VISIBLE);
                adItem.onExposured(mView.findViewById(R.id.nativeADContainertwo)); // 需要先调用曝光接口
                mView.findViewById(R.id.nativeADContainertwo).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        adItem.onClicked(view); // 点击接口
                        reportAdClick();
                    }
                });
                new Thread(){
                    @Override
                    public void run() {
                        bmp =  ImageLoader.getInstance().loadImageSync(adItem.getImgUrl());
                    }
                }.start();

                new Handler().postDelayed(new Runnable(){

                    public void run() {
                        if(!TextUtils.isEmpty(adItem.getImgUrl()) && null != bmp){
                            Bitmap myBitmap = Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth() / 3) , (int)(bmp.getHeight() / 3), true);
                            ((ImageView)mView.findViewById(R.id.gdt_right_bg)).setImageBitmap(BitmapUtils.fastBlur(myBitmap, 5));
                        }
                    }

                }, 300);
            }
        }else if("focus".equals(type)){ //焦点图
            $.id(R.id.ad_text_mark_tv_one).visible();
            $.id(R.id.ad_logo_iv).visible();
            $.id(R.id.ad_logo_iv).image(R.drawable.gdt_ad_logo);
            $.id(R.id.focus_item_image).image(adItem.getImgUrl(), true, true);
            $.id(R.id.focus_item_tv).text(adItem.getTitle());
            adItem.onExposured(mView); // 需要先调用曝光接口
            mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    adItem.onClicked(view); // 点击接口
                    reportAdClick();
                }
            });
        } else if (TextUtils.equals("exit", type)) {
            $.id(R.id.ad_tips_tv).visible();
            $.id(R.id.ad_logo_iv).visible();
            $.id(R.id.ad_logo_iv).image(R.drawable.gdt_ad_logo);
            ImageLoader.getInstance().displayImage(adItem.getImgUrl(), (ImageView) mView.findViewById(R.id.iv_main));
            adItem.onExposured(mView);
            mView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    adItem.onClicked(view);
                    reportAdClick();
                }
            });
        } else if(TextUtils.equals("pause", type)){
            mView.findViewById(R.id.ad_logo_iv).setVisibility(View.VISIBLE);
            mView.findViewById(R.id.pause_ad_image).setVisibility(View.VISIBLE);
            mView.findViewById(R.id.ad_close_iv).setVisibility(View.VISIBLE);
            mView.findViewById(R.id.ad_tips_tv).setVisibility(View.VISIBLE);
            mView.findViewById(R.id.baidu_inter_ad_rl).setVisibility(View.GONE);
            $.id(R.id.ad_logo_iv).image(R.drawable.gdt_ad_logo);
            $.id(R.id.pause_ad_image).image(adItem.getImgUrl(), true, true);
            adItem.onExposured(mView); // 需要先调用曝光接口
            mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    adItem.onClicked(view); // 点击接口
                    reportAdClick();
                }
            });
            mView.findViewById(R.id.ad_close_iv).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mView.setVisibility(View.GONE);
                    reportAdClose();
                }
            });
        } else if (TextUtils.equals("attach", type)) {
            mView.setVisibility(View.VISIBLE);
            mView.findViewById(R.id.iv_attach_photo).setVisibility(View.VISIBLE);
            $.id(R.id.iv_attach_photo).image(adItem.getImgUrl(), false, true);
            adItem.onExposured(mView);
            mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    adItem.onClicked(view); // 点击接口
                    reportAdClick();
                }
            });
        } else if (TextUtils.equals("recom",type)) {
            mView.setVisibility(View.VISIBLE);
            $.id(R.id.relative_ad_title).text(adItem.getTitle());
            $.id(R.id.relative_ad_desc).text(adItem.getDesc());
            $.id(R.id.relative_img_ad).image(adItem.getImgUrl(), false, true);
            $.id(R.id.relative_img_ad_source).image(R.drawable.gdt_ad_logo);
            adItem.onExposured(mView);
            mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    adItem.onClicked(view); // 点击接口
                    reportAdClick();
                }
            });
        }
    }

    /**
     * App类广告安装、下载状态的更新（普链广告没有此状态，其值为-1） 返回的AppStatus含义如下： 0：未下载 1：已安装 2：已安装旧版本 4：下载中（可获取下载进度“0-100”）
     * 8：下载完成 16：下载失败
     */
    private String getADButtonText() {
        if (adItem == null) {
            return "……";
        }
        if (!adItem.isAPP()) {
            return "查看详情";
        }
        switch (adItem.getAPPStatus()) {
            case 0:
                return "点击下载";
            case 1:
                return "点击启动";
            case 2:
                return "点击更新";
            case 4:
                return adItem.getProgress() > 0 ? "下载中" + adItem.getProgress()+ "%" : "下载中"; // 特别注意：当进度小于0时，不要使用进度来渲染界面
            case 8:
                return "下载完成";
            case 16:
                return "下载失败,点击重试";
            default:
                return "查看详情";
        }
    }

    @Override
    public void onADLoaded(List<NativeADDataRef> arg0) {
        if (arg0.size() > 0) {
            if ("attach".equals(type) && isOutTimeControlInVideoDetail) {
                return;
            }
            isOutTimeControlInVideoDetail = true;
            adItem = arg0.get(0);
//            Toast.makeText(activity, "原生广告加载成功", Toast.LENGTH_LONG).show();
            reportAdSuccess();
            if(adListener != null){
                if("splash".equals(type)){
                    if(isOutTimeJump){
                      return;
                    }else{
                        splashIsResponse = true;
                    }
                }
                adListener.onAdSuccess(arg0);
                if(!"exit".equals(type)){
                    showAD(type);
                }
            }else{
                showAD(type);
            }
        } else {
            Log.i("AD_DEMO", "NOADReturn");
            reportAdRequestError();
            if(adListener != null){
                if(!isOutTimeJump && "splash".equals(type)){
                    splashIsResponse = true;
                }
                adListener.onAdFailed();
            }
        }
    }

    @Override
    public void onADStatusChanged(NativeADDataRef arg0) {
//        $.id(R.id.btn_download).text(getADButtonText());
    }

    @Override
    public void onADError(NativeADDataRef adData, int errorCode) {
        Log.i("AD_DEMO", "onADError:" + errorCode);
        if ("attach".equals(type) && isOutTimeControlInVideoDetail) {
            return;
        }
        isOutTimeControlInVideoDetail = true;
        reportAdError(errorCode);
        if(adListener != null){
            adListener.onAdFailed();
        }
    }

    @Override
    public void onNoAD(int arg0) {
        Log.i("AD_DEMO", "ONNoAD:" + arg0);
        if ("attach".equals(type) && isOutTimeControlInVideoDetail) {
            return;
        }
        isOutTimeControlInVideoDetail = true;
        reportAdRequestError();
        if(adListener != null){
            if(!isOutTimeJump && "splash".equals(type)){
                splashIsResponse = true;
            }
            adListener.onAdFailed();
        }
    }

    private void reportAdSuccess(){
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        gdtPropertyMap.put("result", "success");
        gdtPropertyMap.put("time", (System.currentTimeMillis()-startRequestTime)/1000+"");
        UmengEventPoster.doPost(UmengEventPoster.GDTAD_REQUEST, gdtPropertyMap);

        selfGdtReport(SelfDataConstant.AC_ADREQUEST_SUCCESS);
    }

    private void reportAdRequestError(){
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        gdtPropertyMap.put("result", "fail");
        UmengEventPoster.doPost(UmengEventPoster.GDTAD_REQUEST, gdtPropertyMap);
    }

    private void reportAdError(int code){
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        gdtPropertyMap.put("code", code+"");
        UmengEventPoster.doPost(UmengEventPoster.GDTAD_ERROE, gdtPropertyMap);

        selfGdtReport(SelfDataConstant.AC_ADREQUEST_FAIL);
    }

    private void reportAdShow() {
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        UmengEventPoster.doPost(UmengEventPoster.GDTAD_SHOW, gdtPropertyMap);

        selfGdtReport(SelfDataConstant.AC_ADSHOW);
    }

    private void reportAdClick() {
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        UmengEventPoster.doPost(UmengEventPoster.GDTAD_CLICK, gdtPropertyMap);

        selfGdtReport(SelfDataConstant.AC_ADCLICK);
    }

    private void reportAdClose() {
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        UmengEventPoster.doPost(UmengEventPoster.GDTAD_CLOSE, gdtPropertyMap);
    }

    private void reportAdRequestVtwo(){
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        UmengEventPoster.doPost(UmengEventPoster.GDTAD_REQUEST_VTWO, gdtPropertyMap);

        selfGdtReport(SelfDataConstant.AC_SDKAD_REQUEST);
    }

    private void selfGdtReport(String acode){
        MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
        record.setAcode(acode);
        record.setAd_pro(SelfDataConstant.AD_GDT);
        record.setAd_po(mAdposition);
        record.setUsergroup(BigDataConstants.AUID.hashCode()%10 + "");
        RealmDaoManager.addMyDataRecord(record);
    }

    private void reportGdtOutTime() {
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        UmengEventPoster.doPost(UmengEventPoster.GDTAD_TIMEOUT, gdtPropertyMap);
    }
}
